<template>
  <div style="width:95%;margin:auto;margin-top:20px">
    <el-table
      :data="tmpData"
      style="width: 100%"
      size="medium"
      :fit="true"
      :border="true"
      stripe
      highlight-current-row
    >
      <!-- <el-table-column
        label="序号"
        type="index"
        width="160px"
        align="center"
      /> -->
      <el-table-column label="任务名称" prop="name" align="center" />
      <el-table-column label="秒杀图书" prop="bookName" align="center" />
      <el-table-column label="任务触发周期" prop="corn" align="center" />
      <el-table-column label="任务开始时间" prop="startTime" />
      <el-table-column label="任务结束时间" prop="endTime" />
      <!-- <el-table-column label="持续时间(秒)" prop="second" align="center" /> -->
      <el-table-column label="任务状态" prop="status" align="center" :formatter="handleFormatStatus" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button-group>
            <el-button
              v-if="scope.row.status === 0"
              size="mini"
              type="success"
              @click="startSchedule(scope.$index, scope.row)"
            >开启</el-button>
            <el-button
              v-if="scope.row.status === 1"
              size="mini"
              type="success"
              @click="downSchedule(scope.$index, scope.row)"
            >关闭</el-button>
            <!-- <el-button
              size="mini"
              @click="handleEditBook(scope.$index, scope.row)"
            >更改活动 </el-button>
            <el-button
              size="mini"
              @click="handleEditTime(scope.$index, scope.row)"
            >更改时间</el-button> -->
            <el-button
              size="mini"
              type="danger"
              @click="deleteSchedule(scope.$index, scope.row)"
            >删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px">
      <el-button type="primary" @click="add()">添加任务</el-button>
      <!-- <el-button type="warning" @click="deleteAll()">清空所有任务</el-button> -->
      <el-button type="warning" @click="handeleOutExportExcel">导出</el-button>
      <div class="block" style="float: right;">
        <!-- <span class="demonstration">调整每页显示条数</span> -->
        <el-pagination
          :current-page.sync="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="sizes, prev, pager, next"
          :total="totalSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <transition name="el-fade-in-linear">
      <el-dialog :visible.sync="showAdd">
        <el-form ref="addData" :model="addData" label-width="160px">
          <el-form-item label="活动名称">
            <el-input v-model="addData.name" />
          </el-form-item>
          <el-form-item label="活动触发周期">
            <el-cascader
              v-model="corn"
              :options="cornOptions"
              :disabled="cornEnable"
              @change="handleChangeCorn"
            />
            <el-input v-model="addData.corn" style="width: 400px" :disabled="!cornEnable" />
            <el-switch
              v-model="cornEnable"
              style="margin-right:10px"
              active-text="自定义已开启"
              inactive-text="自定义未开启"
            />
            <p> 跳转到CRON规则生成<i class="el-icon-s-promotion" @click="moveToCorn" /></p>
          </el-form-item>
          <el-form-item label="活动时间">
            <div class="block">
              <el-date-picker
                v-model="date"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleSelectAddDate"
              />
            </div>
          </el-form-item>
          <!-- <el-form-item label="持续时间">
            <el-input-number v-model="second" style="margin-right:40px" :min="1" :max="60" label="个数" @change="handleChangeSecond" />
            <el-radio-group v-model="radio" @change="handleChangeSecond">
              <el-radio :label="0">秒</el-radio>
              <el-radio :label="1">分钟</el-radio>
              <el-radio :label="2">时钟</el-radio>
              <el-radio :label="3">天</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <el-form-item label="图书名称">
            <el-autocomplete
              v-model="bookName"
              class="inline-input"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              :trigger-on-focus="false"
              @select="handleSelectBookName"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="float:right" @click="doAdd">立即创建</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </transition>

  </div>
</template>

<script>
import { getSchedule, addSchedule, getBookNames, delSchedule, startSchedule } from '@/utils/book'
import { outExportExcel } from '@/api/exportData.js'
export default {
  data() {
    return {
      tableData: [],
      tmpData: [],
      currentPage: 1,
      totalSize: 1,
      pageSize: 5,
      addData: {},
      corn: [],
      cornOptions: [],
      showAdd: false,
      date: '',
      radio: 0,
      second: 0,
      radioT: [1, 60, 60 * 60, 60 * 60 * 24],
      zhouList: ['MON', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'],
      bookNames: [],
      bookName: '',
      cornEnable: false
    }
  },
  created() {
    const vm = this
    this.createOption()
    getBookNames().then(res => {
      res.object.forEach(element => {
        this.bookNames.push({ 'value': element })
      })
    })
    getSchedule({ isAll: true }).then(res => {
      vm.tableData = res.object
      vm.handleSizeChange(vm.pageSize)
      vm.totalSize = vm.tableData.length
    })
  },
  methods: {
    moveToCorn() {
      window.open('https://qqe2.com/cron')
    },
    startSchedule(idx, row) {
      const vm = this
      startSchedule({ 'id': row.id, 'name': row.name, 'status': 1 }).then(res => {
        if (res.code === 200) {
          this.$message.info('启动成功')
        } else {
          this.$message.info('启动失败')
        }
      }).then(() => {
        getSchedule({ 'isAll': true }).then(res => {
          vm.tableData = res.object
          vm.handleSizeChange(vm.pageSize)
          vm.totalSize = vm.tableData.length
        })
      })
    },
    downSchedule(idx, row) {
      const vm = this
      startSchedule({ 'id': row.id, 'name': row.name, 'status': 0 }).then(res => {
        if (res.code === 200) {
          this.$message.info('关闭成功')
        } else {
          this.$message.info('关闭失败')
        }
      }).then(() => {
        getSchedule({ 'isAll': true }).then(res => {
          console.log(res.object)
          vm.tableData = res.object
          vm.handleSizeChange(vm.pageSize)
          vm.totalSize = vm.tableData.length
        })
      })
    },
    formateDate(datetime) {
      function addDateZero(num) {
        return (num < 10 ? '0' + num : num)
      }
      const d = new Date(datetime)
      const formatdatetime = d.getFullYear() + '-' + addDateZero(d.getMonth() + 1) + '-' + addDateZero(d.getDate()) + ' ' + addDateZero(d.getHours()) + ':' + addDateZero(d.getMinutes()) + ':' + addDateZero(d.getSeconds())
      return formatdatetime
    },
    handleChangeCorn() {
      this.addData['corn'] = this.corn[this.corn.length - 1]
      console.log(this.addData)
    },
    handleSelectBookName() {
      this.addData['bookName'] = this.bookName
    },
    querySearch(queryString, cb) {
      var restaurants = this.bookNames
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        console.log(typeof (restaurant))
        return (restaurant.value.indexOf(queryString) === 0)
      }
    },
    // handleChangeSecond() {
    //   this.addData['second'] = this.second * this.radioT[this.radio]
    // },
    handleSelectAddDate(date) {
      this.addData['startTime'] = this.formateDate(date[0])
      this.addData['endTime'] = this.formateDate(date[1])
      console.log(this.addData)
    },
    handleChange(value) {
      // console.log(value)
      this.addData['corn'] = value[value.length - 1]
      console.log(this.addData)
    },
    createdDayList() {
      var dayList = []
      for (var i = 0; i < 24; i++) {
        dayList.push({
          value: 'error',
          label: i + '点',
          children: this.createdDayHourList(i)
        })
      }
      return dayList
    },
    createdDayHourList(i) {
      var hourList = []
      // hourList.push({
      //   value: '0 0 ' + i + ' * * ?',
      //   label: '00' + '分'
      // })
      // hourList.push({
      //   value: '0 15 ' + i + ' * * ?',
      //   label: '15' + '分'
      // })
      // hourList.push({
      //   value: '0 30 ' + i + ' * * ?',
      //   label: '30' + '分'
      // })
      // hourList.push({
      //   value: '0 45 ' + i + ' * * ?',
      //   label: '45' + '分'
      // })
      for (let t = 0; t < 60; t++) {
        hourList.push({
          value: '0 ' + t + ' ' + i + ' * * ?',
          label: t + '分'
        })
      }
      return hourList
    },
    createdZhouDayList(i) {
      var dayList = []
      for (let j = 0; j < 24; j++) {
        dayList.push({
          value: 'error',
          label: j + '点',
          children: this.createdZhouHourList(j, i)
        })
      }
      return dayList
    },
    createdZhouHourList(i, z) {
      var hourList = []
      // hourList.push({
      //   value: '0 0 ' + i + ' ? * ' + z,
      //   label: '00' + '分'
      // })
      // hourList.push({
      //   value: '0 15 ' + i + ' ? * ' + z,
      //   label: '15' + '分'
      // })
      // hourList.push({
      //   value: '0 30 ' + i + ' ? * ' + z,
      //   label: '30' + '分'
      // })
      // hourList.push({
      //   value: '0 45 ' + i + ' ? * ' + z,
      //   label: '45' + '分'
      // })
      for (let t = 0; t < 60; t++) {
        hourList.push({
          value: '0 ' + t + ' ' + i + ' ? * ' + this.zhouList[z],
          label: t + '分'
        })
      }
      return hourList
    },
    createdZhouList() {
      var zhouList = []
      var zhou = ['一', '二', '三', '四', '五', '六', '日']
      for (var i = 1; i <= 7; i++) {
        zhouList.push({
          value: 'error',
          label: '周' + zhou[i - 1],
          children: this.createdZhouDayList(i)
        })
      }
      return zhouList
    },
    createOption() {
      this.cornOptions.push({
        value: 'error',
        label: '每天',
        children: this.createdDayList()
      })
      this.cornOptions.push({
        value: 'error',
        label: '每周',
        children: this.createdZhouList()
      })
      this.cornOptions.push({
        value: '0/5 * * * * ?',
        label: '不指定'
      })
    },
    add() {
      this.showAdd = true
    },
    doAdd() {
      const vm = this
      addSchedule(this.addData).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message.info('添加成功')
        } else {
          this.$message.info('添加失败')
        }
        this.showAdd = false
      }).then(res => {
        getSchedule({ 'isAll': true }).then(res => {
          vm.tableData = res.object
          vm.handleSizeChange(vm.pageSize)
          vm.totalSize = vm.tableData.length
        })
      }
      )
    },
    deleteSchedule(idx, row) {
      console.log(row)
      const vm = this
      delSchedule({ 'id': row.id }).then(res => {
        if (res.code === 200) {
          this.$message.info('删除成功')
        } else {
          this.$message.info('删除失败')
        }
      }).then(function() {
        getSchedule({ 'isAll': true }).then(res => {
          vm.tableData = res.object
          vm.handleSizeChange(vm.pageSize)
          vm.totalSize = vm.tableData.length
        })
      })
    },
    doDelete() {

    },
    deleteAll() {
    },
    handleFormatStatus(row, column, cellValue, index) {
      if (cellValue === 0) {
        return '关闭'
      }
      return '开启'
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
      const start = (this.currentPage - 1) * this.pageSize
      var step = start + this.pageSize > this.tableData.length ? this.tableData.length : start + this.pageSize
      this.tmpData = this.tableData.slice(start, step)
      console.log(this.tmpData)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      const start = (this.currentPage - 1) * this.pageSize
      var step = start + this.pageSize > this.tableData.length ? this.tableData.length : start + this.pageSize
      this.tmpData = this.tableData.slice(start, step)
      console.log(this.tmpData)
    },
    handeleOutExportExcel() {
      const tableHeader = ['ID', '任务名称', '任务触发周期', '秒杀图书', '开始时间', '结束时间', '状态']
      const tableKey = ['id', 'name', 'corn', 'bookName', 'startTime', 'endTime', 'status']
      outExportExcel(
        tableHeader,
        tableKey,
        this.tableData
      )
    }
  }
}
</script>
<style  lang="scss" scoped>

</style>
